﻿using WeiXin.Base.Pay.Lib;

namespace WeiXin.Base.Pay
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// 扫码支付
    /// </summary>
    public class NativePay
    {
        /// <summary>
        /// 生成扫描支付模式一URL
        /// </summary>
        /// <remarks>开发步骤：https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=6_3</remarks>
        /// <param name="productId">商品ID或订单ID</param>
        /// <returns>模式一URL</returns>
        public string GetPrePayUrl(string productId)
        {
            #region 生成扫描支付模式一URL
            WxPayLog.Info(this.GetType().ToString(), "Native pay mode 1 url is producing...");

            WxPayData data = new WxPayData();
            data.SetValue("appid", WxPayConfig.APPID);//公众帐号id
            data.SetValue("mch_id", WxPayConfig.MCHID);//商户号
            data.SetValue("time_stamp", WxPayApi.GenerateTimeStamp());//时间戳
            data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());//随机字符串
            data.SetValue("product_id", productId);//商品ID
            data.SetValue("sign", data.MakeSign());//签名
            string str = ToUrlParams(data.GetValues());//转换为URL串
            string url = "weixin://wxpay/bizpayurl?" + str;

            WxPayLog.Info(this.GetType().ToString(), "Get native pay mode 1 url : " + url);
            return url; 
            #endregion
        }

        /// <summary>
        /// 生成直接支付url，支付url有效期为2小时,模式二
        /// </summary>
        /// <remarks>开发步骤：https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=6_3</remarks>
        /// <param name="productId">商品ID（订单中包含的商品ID）</param>
        /// <param name="out_trade_no">商户订单号（建议根据当前系统时间加随机序列来生成订单号，长度不超过32位）</param>
        /// <param name="total_fee">订单总金额(单位：分)</param>
        /// <param name="body">商品或支付单简要描述（长度不超过127个字符）</param>
        /// <param name="goods_tag">商品标记，代金券或立减优惠功能的参数</param>
        /// <param name="attach">订单附加数据(在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据)</param> 
        /// <returns>模式二URL</returns>
        public string GetPayUrl(string productId, string out_trade_no, string total_fee, string body, string goods_tag = "", string attach = "")
        {
            #region 生成直接支付url，支付url有效期为2小时,模式二
            WxPayLog.Info(this.GetType().ToString(), "Native pay mode 2 url is producing...");

            WxPayData data = new WxPayData();
            data.SetValue("body", body);//商品描述
            data.SetValue("out_trade_no", out_trade_no);//商户订单号
            data.SetValue("total_fee", int.Parse(total_fee));//总金额
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));//交易结束时间
            data.SetValue("goods_tag", goods_tag);//商品标记
            data.SetValue("trade_type", "NATIVE");//交易类型
            data.SetValue("product_id", productId);//商品ID
            data.SetValue("attach", attach);//附加数据

            WxPayData result = WxPayApi.UnifiedOrder(data);//调用统一下单接口
            string url = result.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接

            WxPayLog.Info(this.GetType().ToString(), "Get native pay mode 2 url : " + url);
            return url; 
            #endregion
        }

        /// <summary>
        /// 参数数组转换为url格式
        /// </summary>
        /// <param name="map">参数名与参数值的映射表</param>
        /// <returns>URL字符串</returns>
        private string ToUrlParams(SortedDictionary<string, object> map)
        {
            #region 参数数组转换为url格式
            string buff = "";
            foreach (KeyValuePair<string, object> pair in map)
            {
                buff += pair.Key + "=" + pair.Value + "&";
            }
            buff = buff.Trim('&');
            return buff; 
            #endregion
        }
    }
}